<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="用户id" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable  />
      </el-form-item> -->

      <el-form-item  label="时间区间" prop="addtime">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="value2"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="变动类型"  prop="addtime">
        <el-select v-model="payType" placeholder="请选择购买方式">
          <el-option
            v-for="dict in dict.type.chang_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="用户类型"  prop="addtime">
        <el-select v-model="userType" placeholder="请选择购买方式">
          <el-option
            v-for="dict in [
              { value: '0', key: '0', label: '普通用户' },
              { value: '1', key: '1', label: '特权账号' },
            ]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="变动类型"  prop="addtime">
        <el-select v-model="type" placeholder="请选择购买方式">
          <el-option
            v-for="dict in [
              { value: 0, key: 0, label: '积分变动' },
              { value: 1, key: 1, label: 'Mb变动' },
              { value: 2, key: 2, label: '余额变动' },
            ]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >

        <span style="font-size: 30px; margin-left: 20px">{{ this.sum }}</span>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:money:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:money:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:money:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:money:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="moneyList"
      @sort-change="dataListSortChangeHandle"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="用户" align="center" prop="username" width="200">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center">
            <el-avatar :src="scope.row.headImgurl"></el-avatar>
            <div>{{ scope.row.username }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        sortable="custom"
        label="变化的金额"
        align="center"
        prop="change"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.change > 0">+{{ scope.row.change }}</el-tag>
          <el-tag type="danger" v-else>{{ scope.row.change }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="变动类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 1">后台充值</el-tag>
          <el-tag v-if="scope.row.type == 2" type="success">在线充值</el-tag>
          <el-tag v-if="scope.row.type == 3" type="warning">消费</el-tag>
          <el-tag v-if="scope.row.type == 4" type="danger">提现</el-tag>
          <el-tag v-if="scope.row.type == 5" type="info">体现返还</el-tag>
          <el-tag v-if="scope.row.type == 6">商品回收</el-tag>
          <el-tag v-if="scope.row.type == 7" type="success">商品专卖</el-tag>
          <el-tag v-if="scope.row.type == 8" type="warning">商城折扣</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="管理员id" align="center" prop="adminId" />

      <el-table-column
        label="创建时间"
        align="center"
        prop="addtime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
          scope.row.createDate
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:money:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>
  </div>
</template>

<script>
import {
  listMoney,
  getMoney,
  delMoney,
  addMoney,
  updateMoney,
} from "@/api/users/consume.js";
import {
  getMy_user_chang,
  getMy_user,
  getMy_user_chang_jf,
} from "@/api/users/user.js";

export default {
  dicts: ["chang_type"],
  name: "Biandong",

  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      sum: 0,
      payType: "1",
      userType: "0",

      value2: [],
      chang_type: 1,
      type: 2,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 财务明细表格数据
      moneyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: this.ID,
        money: null,
        change: null,
        type: null,
        adminId: null,
        addtime: null,
        creator: null,
        createDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" },
        ],
        type: [
          {
            required: true,
            message:
              "类型，1 后台充值 2在线充值 3 消费 4 提现 5 提现返还 6商品回收 7 商品转卖 8商城抵扣不能为空",
            trigger: "change",
          },
        ],
        addtime: [
          { required: true, message: "添加时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.gettime();
    this.getList();
  },
  methods: {
    //查询用户信息
    async queryUser(arr) {
      let val = arr;
      for (let index = 0; index < arr.length; index++) {
        console.log(arr[index].userId);
        await getMy_user(arr[index].userId).then((response) => {
          if (response.data) {
            this.$set(
              this.moneyList[index],
              "username",
              response.data.nickname
            );
            this.$set(this.moneyList[index], "headimg", response.data.headimg);
          }
        });
      }
    },
    msToDate(msec) {
      let datetime = new Date(msec);
      let year = datetime.getFullYear();
      let month = datetime.getMonth();
      let date = datetime.getDate();
      let hour = datetime.getHours();
      let minute = datetime.getMinutes();
      let second = datetime.getSeconds();

      let result1 =
        year +
        "-" +
        (month + 1 >= 10 ? month + 1 : "0" + (month + 1)) +
        "-" +
        (date + 1 < 10 ? "0" + date : date) +
        " " +
        (hour + 1 < 10 ? "0" + hour : hour) +
        ":" +
        (minute + 1 < 10 ? "0" + minute : minute) +
        ":" +
        (second + 1 < 10 ? "0" + second : second);

      let result2 =
        year +
        "-" +
        (month + 1 >= 10 ? month + 1 : "0" + (month + 1)) +
        "-" +
        (date + 1 < 10 ? "0" + date : date);

      let result = {
        hasTime: result1,
        withoutTime: result2,
      };

      return result;
    },

    gettime(val) {
      //获取前一天及今天的数据
      let ts_begin = new Date();
      let ts_end = new Date();
      ts_begin.setTime(
        ts_begin.getTime() -
          3600 * 1000 * ts_begin.getHours() -
          60 * 1000 * ts_begin.getMinutes() -
          1000 * ts_begin.getSeconds()
      );
      ts_end.setTime(ts_begin.getTime() + 3600 * 1000 * 24 - 1000);
      //格式化Sat Jul 23 2022 00:00:00 GMT+0800 (中国标准时间)

      this.value2 = [
        this.msToDate(ts_begin).hasTime,
        this.msToDate(ts_end).hasTime,
      ];
      console.log(this.value2);
    },

    /** 查询财务明细列表 */
    getList() {
      this.loading = true;
      if (this.type == 2) {
        getMy_user_chang({
          start: this.value2[0],
          end: this.value2[1],
          type: this.payType,
          ifPrivate: this.userType,
        }).then((response) => {
          console.log(response);
          this.moneyList = response.data.list;
          this.sum = response.data.sum;
          //  this.queryUser(this.moneyList)
          // this.total = response.total;
          this.loading = false;
        });
      } else {
        getMy_user_chang_jf({
          ifMb: this.type,
          ifPrivate: this.userType,
          start: this.value2[0],
          end: this.value2[1],
          type: this.payType,
        }).then((response) => {
          console.log(response);
          this.moneyList = response.data.list;
          this.sum = response.data.sum;
          //  this.queryUser(this.moneyList)
          // this.total = response.total;
          this.loading = false;
        });
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        money: null,
        change: null,
        type: null,
        adminId: null,
        addtime: null,
        creator: null,
        createDate: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.orderByColumn = "";
      this.queryParams.isAsc = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加财务明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMoney(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改财务明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMoney(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMoney(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除财务明细编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMoney(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/money/export",
        {
          ...this.queryParams,
        },
        `money_${new Date().getTime()}.xlsx`
      );
    },
    //排序
    dataListSortChangeHandle(data) {
      if (!data.order || !data.prop) {
        this.queryParams.orderByColumn = "";
        this.queryParams.isAsc = "";
        return false;
      }
      this.queryParams.isAsc = data.order.replace(/ending$/, "");
      this.queryParams.orderByColumn = data.prop
        .replace(/([A-Z])/g, "_$1")
        .toLowerCase();
      this.getList();
    },
  },
};
</script>
